package com.qf.Web.Servlet;

import cn.dsna.util.images.ValidateCode;
import com.qf.Domain.Address;
import com.qf.Domain.User;
import com.qf.Service.Impl.UserServiceImpl;
import com.qf.Service.UserService;
import com.qf.Utils.Base64Utils;
import com.qf.Utils.RandomUtils;
import com.qf.Utils.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/*
 *
 */
@WebServlet(name = "UserServlet",value = "/userservlet")
public class UserServlet extends BaseServlet {
    //注册
    public String register(HttpServletRequest request, HttpServletResponse response){
        //接收数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        //判断空值
        if (StringUtils.isEmtry(username)){
            request.setAttribute("registerMsg", "用户名不能为空");
            return "/register.jsp";
        }
        if (StringUtils.isEmtry(password)){
            request.setAttribute("registerMsg", "密码不能为空");
            return "/register.jsp";
        }
        if (password.length()<6||password.length()>12){
            request.setAttribute("registerMsg", "密码长度不符合要求");
            return "/register.jsp";
        }
        if (!password.equals(repassword)){
            request.setAttribute("registerMsg", "两次密码不一致");
            return "/register.jsp";
        }
        if (StringUtils.isEmtry(email)){
            request.setAttribute("registerMsg", "邮箱不能为空");
            return "/register.jsp";
        }
        if (StringUtils.isEmtry(gender)){
            request.setAttribute("registerMsg", "性别不能为空");
            return "/register.jsp";
        }
        User user=new User(0, username, password, email, gender, 0, 1, RandomUtils.createActive());
        UserService userService=new UserServiceImpl();
        try {
            userService.insert(user);
            return "registerSuccess.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("registerMsg", "注册失败"+e.getMessage());
            return "/register.jsp";
        }
    }
    //检查用户名是否存在
    public String checkUserName(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String username = request.getParameter("username");
        //System.out.println(username);
        if (StringUtils.isEmtry(username)){
            response.getWriter().write("1");
            return null;
        }
        UserService userService=new UserServiceImpl();
        boolean b = userService.select(username);
        //System.out.println(b);
        if (b){
            response.getWriter().write("1");
        }else {
            response.getWriter().write("0");
        }
        return null;
    }
    //验证码
    public String code(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //设置响应头解决缓存问题
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("pragma", "no-cache");
        //创建ValidateCode对象
        ValidateCode validateCode=new ValidateCode(150, 30, 4, 20);
        String code = validateCode.getCode();
        request.getSession().setAttribute("code", code);
        validateCode.write(response.getOutputStream());
        return  null;
    }
    //登录
    public String login(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");
        String auto = request.getParameter("auto");
        String code = (String) request.getSession().getAttribute("code");
        //判断
        if (StringUtils.isEmtry(username)){
            request.setAttribute("msg", "用户名不能为空");
            return "/login.jsp";
        }
        if (StringUtils.isEmtry(password)){
            request.setAttribute("msg", "密码不能为空");
            return "/login.jsp";
        }
        if (StringUtils.isEmtry(vcode)){
            request.setAttribute("msg", "验证码不能为空");
            return "/login.jsp";
        }
        if (!vcode.equalsIgnoreCase(code)){
            request.setAttribute("msg", "验证码错误");
            return "/login.jsp";
        }
        UserService userService=new UserServiceImpl();
        try {
            User user = userService.select(username, password);
            if (user!=null) {
                if (auto!=null){
                    String userInfo=username+"#"+password;
                    userInfo = Base64Utils.encode(userInfo);
                    Cookie cookie=new Cookie("userInfo",userInfo);
                    cookie.setPath(request.getContextPath());
                    cookie.setMaxAge(60*60*24*7);
                    cookie.setHttpOnly(true);
                    response.addCookie(cookie);
                }else {
                    Cookie cookie2=new Cookie("userInfo","");
                    cookie2.setPath(request.getContextPath());
                    cookie2.setMaxAge(0);
                    cookie2.setHttpOnly(true);
                    response.addCookie(cookie2);
                }
                request.getSession().setAttribute("user", user);
                return "redirect:/index.jsp";
            }else {
                request.setAttribute("msg", "用户名或密码错误");
                return "/login.jsp";
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", e.getMessage());
            return "/login.jsp";
        }
    }
    //注销
    public String logOut(HttpServletRequest request,HttpServletResponse response){
        //移除session中的user
        request.getSession().removeAttribute("user");
        //移除cookie
        Cookie cookie=new Cookie("userInfo", "");
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        //是session失效
        request.getSession().invalidate();
        return "/index.jsp";
    }
    //管理地址
    public String getAddress(HttpServletRequest request,HttpServletResponse response){
        //判断用户是否登录
        User  user = (User) request.getSession().getAttribute("user");
        if (user==null){
            return "redirect:/login.jsp";
        }
        UserService userService=new UserServiceImpl();
        try {
            List<Address> address = userService.findAddress(user.getId());
            request.setAttribute("addList",address);
            return "/self_info.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","获取地址失败");
            return "/message.jsp";
        }
    }
    //添加地址
    public String addAddress(HttpServletRequest request,HttpServletResponse response){
        //判断用户是否登录
        User  user = (User) request.getSession().getAttribute("user");
        if (user==null){
            return "redirect:/login.jsp";
        }
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        if (StringUtils.isEmtry(name)){
            request.setAttribute("msg", "姓名不能为空");
        }
        if (StringUtils.isEmtry(phone)){
            request.setAttribute("msg", "电话不能为空");
        }
        if (StringUtils.isEmtry(detail)){
            request.setAttribute("msg", "地址不能为空");
        }
        Address address=new Address(0, detail, name, phone, user.getId(), 0);
        UserService userService=new UserServiceImpl();
        try {
            userService.addAddress(address);
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "添加地址失败");
            return "/message.jsp";
        }
    }
    //设置默认地址
    public String defaultAddress(HttpServletRequest request,HttpServletResponse response){
        User  user = (User) request.getSession().getAttribute("user");
        if (user==null){
            return "redirect:/login.jsp";
        }
        String id = request.getParameter("id");
        if (StringUtils.isEmtry(id)){
            return null;
        }
        UserService userService=new UserServiceImpl();
        try {
            userService.updateAddressStatus(user.getId(),Integer.parseInt(id));
            return "redirect:/userservlet?method=getAddress";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            request.setAttribute("msg", "修改默认地址失败");
            return "/message.jsp";
        }
    }
    //修改地址
    public String updateAddress(HttpServletRequest request,HttpServletResponse response) throws Exception{
        User  user = (User) request.getSession().getAttribute("user");
        if (user==null){
            return "redirect:/login.jsp";
        }
        String id = request.getParameter("id");
        String level = request.getParameter("level");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        response.setContentType("text/html;charset=utf-8");
        if (StringUtils.isEmtry(id)){
            response.getWriter().write("<script>alert('id不能为空');</script>");
            return null;
        }
        if (StringUtils.isEmtry(level)){
            response.getWriter().write("<script>alert('地址状态不能为空');</script>");
            return null;
        }
        if (StringUtils.isEmtry(name)){
            response.getWriter().write("<script>alert('姓名不能为空');</script>");
            return null;
        }
        if (StringUtils.isEmtry(phone)){
            response.getWriter().write("<script>alert('电话不能为空');</script>");
            return null;
        }
        if (StringUtils.isEmtry(detail)){
            response.getWriter().write("<script>alert('地址信息不能为空');</script>");
            return null;
        }
        Address address=new Address(Integer.parseInt(id), detail, name, phone, user.getId(), Integer.parseInt(level));
        UserService userService=new UserServiceImpl();
        try {
            userService.updateAddress(address);
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("<script>alert('修改地址信息失败');</script>");
            return null;
        }
    }
    //删除地址
    public String deleteAddress(HttpServletRequest request,HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        String id = request.getParameter("id");
        response.setContentType("text/html;charset=utf-8");
        if (StringUtils.isEmtry(id)) {
            response.getWriter().write("<script>alert('id不能为空');</script>");
            return null;
        }
        UserService userService = new UserServiceImpl();
        try {
            userService.delete(Integer.parseInt(id));
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("<script>alert('修改地址信息失败');</script>");
            return null;
        }
    }
}
